<template>
    <div class="channelCondition">
        <!-- <nutbTitle title="通道设置"></nutbTitle> -->
        <NuVerifyForm :model="formData" ref="formData" label-width="100px" class="searchForm" @searchForm="searchForm"
            :buttons="fyButtons">
            <NuformItem label="通道名称" prop="channelName" width="auto">
                <nu-input type="text" v-model="formData.channelName" size="middle" placeholder="通道名称"></nu-input>
            </NuformItem>
            <div class="btnBox">
                <nu-button type="primary" class="searchButton" @click="searchTable">搜索</nu-button>
                <nu-button class="searchButton" @click="clearParams">清除</nu-button>
            </div>
        </NuVerifyForm>
        <div class="line"></div>
        <div style="height:35px;position: relative;padding: 0 10px;" class="renovateTime">
            <nu-button class="searchButton" @click="addTable">新增</nu-button>
            <el-dropdown split-button size="medium" type="primary" @command="handleCommand" @click="renovateTimeClick"
                trigger="click" class="dropdownBtn">
                刷新
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="a">每1min自动刷新</el-dropdown-item>
                    <el-dropdown-item command="b">每2min自动刷新</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
        </div>
        <NuTableList :showFilter="false" :columns="columns" :dataSource="dataSource" :options="options"
            :operates="operates(this)" :pagination="pagination" @handleSizeChange="handleSizeChange"
            @handleChangePage="handleChangePage" @handleCurrentChange="handleCurrentChange" v-loading="tableLoading">
        </NuTableList>
        <!-- 新增 -->
        <nu-dialog :title="dialogTitle" :visible.sync="dialogShow" width="46%" center :close-on-click-modal="false"
            top="15vh" :modal-append-to-body="false" @close="diaClose">
            <div class="dialogHeaderSearch">
                <NuVerifyForm :model="dialogFormData" ref="dialogFormData" label-width="110px" class="submitForm"
                    @submitForm="diaSubmitForm" :buttons="fyButtons">
                    <NuformItem label="通道名称" prop="channelName" width="46%"
                        :rules="[{ required: true, message: '通道名称不能为空' }]">
                        <nu-input type="text" v-model="dialogFormData.channelName" size="middle"
                            :disabled="dialogFormDisabled" placeholder="请输入"></nu-input>
                    </NuformItem>
                    <NuformItem label="所属通道组" prop="belongGroupId" width="46%"
                        :rules="[{ required: true, message: '所属通道组不能为空' }]">
                        <nu-select class="searchSelect" :filterable="true" :list="belongGroupIdList" type="text"
                            v-model="dialogFormData.belongGroupId" autocomplete="off" :valueName="'id'" :label="'groupName'"
                            @change="changeBelongGroupName" style="width: calc(100% - 5px);margin-left: 2px;"
                            :disabled="dialogFormDisabled" placeholder="请选择">
                        </nu-select>
                    </NuformItem>
                    <NuformItem label="控制站IP" prop="masterIp" width="46%"
                        :rules="[{ required: true, message: '控制站IP不能为空' }]">
                        <nu-input type="text" v-model="dialogFormData.masterIp" size="middle" :disabled="dialogFormDisabled"
                            placeholder="请输入"></nu-input>
                    </NuformItem>
                    <NuformItem label="受控站IP" prop="slaveIp" width="46%"
                        :rules="[{ required: true, message: '受控站IP不能为空' }]">
                        <nu-input type="text" v-model="dialogFormData.slaveIp" size="middle" :disabled="dialogFormDisabled"
                            placeholder="请输入"></nu-input>
                    </NuformItem>
                    <NuformItem label="端口" prop="port" width="46%" :rules="[{ required: true, message: '端口不能为空且为数字' }]">
                        <nu-input type="number" v-model="dialogFormData.port" size="middle" :disabled="dialogFormDisabled"
                            placeholder="请输入数字类型"></nu-input>
                    </NuformItem>
                    <NuformItem label="通道归属" prop="channelOwner" width="46%"
                        :rules="[{ required: false, message: '通道归属不能为空' }]">
                        <nu-input type="text" v-model="dialogFormData.channelOwner" size="middle"
                            :disabled="dialogFormDisabled" placeholder="请输入"></nu-input>
                    </NuformItem>
                    <!-- <NuformItem label="是否是主通道" prop="identification" width="46%"
                        :rules="[{ required: true, message: '是否是主通道' }]">
                        <el-switch v-model="dialogFormData.identification" active-color="#1890ff" inactive-color="#ff4949">
                        </el-switch>
                    </NuformItem> -->
                </NuVerifyForm>
                <nu-button class="dialogSearchButton" type="primary" @click="diaClose">取消</nu-button>
                <nu-button class="dialogSearchButton" type="primary" @click="diaSave"
                    v-if="dialogTitle == '编辑'">确定</nu-button>
                <nu-button class="dialogSearchButton" type="primary" @click="diaSave"
                    v-if="dialogTitle == '新增'">确定</nu-button>
            </div>
        </nu-dialog>
        <!-- 上传 -->
        <nu-dialog :title="upload.title" :visible.sync="upload.open" width="30%" center :close-on-click-modal="false"
            top="5vh" :modal-append-to-body="false">
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
                :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
                :auto-upload="false" drag :data="upload.data" name="file">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                                                                                                                                                        @click="importTemplate">下载模板</el-link> -->
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </nu-dialog>
    </div>
</template>
    
<script>
import nuCol from "@/components/base/col.vue"
import nutbTitle from "@/components/base/tableTitle.vue"
import NuVerifyForm from "@/components/verify-form"
import NuformItem from "@/components/verify-form/form-item.vue"
import nuInput from "@/components/base/input"
import nuSelect from "@/components/base/select"
import nuButton from "@/components/base/button"
import NuTableList from "@/components/tableList/TableFormList"
import nuDialog from "@/components/base/dialog"
import nuRadio from "@/components/base/radio"
import nuRadioButton from "@/components/base/radio-button"
import axios from 'axios'
import { getToken } from "@/utils/auth";
const operates = that => [
    {
        label: '编辑',
        icon: '',
        width: '50px',
        isShow: row => {
            return true;
        },
        disabled: row => {
            return false;
        },
        method: row => {
            that.openEdit(row);
        },
    },
    {
        label: '副本',
        icon: '',
        width: '50px',
        isShow: row => {
            return true;
        },
        disabled: row => {
            return false;
        },
        method: row => {
            that.copyChannelSet(row);
        },
    },
    {
        isShow: row => {
            return false;
        },
    },
    {
        label: '删除',
        icon: '',
        width: '50px',
        isShow: row => {
            return true;
        },
        disabled: row => {
            return false;
        },
        method: row => {
            that.tbRowdetele(row);
        },
    },
    // {
    //     label: '设置为主通道',
    //     icon: '',
    //     width: '100px',
    //     isShow: row => {
    //         return row.identification != '主通道' ? true : false;
    //     },
    //     disabled: row => {
    //         return false;
    //     },
    //     method: row => {
    //         that.openMainChannel(row);
    //     },
    // }
];
export default {
    name: "channelSet",
    components: { nuCol, nutbTitle, NuVerifyForm, NuformItem, nuInput, nuSelect, nuButton, NuTableList, nuDialog, nuRadio, nuRadioButton },
    data() {
        return {
            formData: { channelName: "" },
            belongGroupIdList: [],
            dialogFormData: {
                identification: true,
                belongGroupId: "",
                belongGroupName: "",
                channelName: "",
                masterIp: "",
                slaveIp: "",
                channelOwner: "",
                port: "",
                channelStatus: 1
            },
            operates,
            fyButtons: [],
            currentRow: null,
            pagination: {
                pageSize: 20,
                total: 0,
                pageNum: 1,
            },
            dialogTitle: '',
            dialogShow: false,
            columns: [
                {
                    label: '序号',
                    prop: 'ranking',
                    width: '70px',
                    render: (h, params) => {
                        return h('span', params.index + 1 + (this.pagination.pageNum - 1) * this.pagination.pageSize);
                    },
                },
                {
                    label: '通道名称',
                    prop: 'channelName',
                },
                {
                    label: '所属通道组',
                    prop: 'belongGroupName',
                },
                {
                    label: '通道归属',
                    prop: 'channelOwner',
                },
                {
                    label: '控制站IP',
                    prop: 'masterIp',
                },
                {
                    label: '受控站IP',
                    prop: 'slaveIp',
                },
                {
                    label: '端口',
                    prop: 'port',
                },
                {
                    label: '通道状态',
                    prop: 'channelStatus',
                    render: (h, params) => {
                        let obj = {
                            1: '离线',
                            0: '在线'
                        }
                        return h('span', obj[params.row.channelStatus] || '离线');
                    },
                },
                {
                    label: '通道标识',
                    prop: 'isOnline',
                    render: (h, params) => {
                        return h('span', params.row.isOnline == 1 ? "主通道" : "—");
                    },
                },
                {
                    label: '刷新时间',
                    prop: 'offlineTime',
                    render: (h, params) => {
                        return h('span', params.row.isOnline == 1 ? params.row.offlineTime : params.row.onlineTime);
                    },
                }
            ],
            dataSource: [{}],
            options: {
                'default-expand-all': true,
                'element-loading-background': 'rgba(225,239,242)',
                'element-loading-text': '数据正在加载中',
                'row-key': 'pid',
                'header-cell-style': {
                    background: 'rgba(105, 159, 209, 0.7)',
                    color: '#fff',
                    fontWeight: 'bold',
                    fontsize: '16px',
                },
                height: 'calc(100vh - 350px)',
                props: {
                    fixed: 'right'
                }
            },
            // 用户导入参数
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + window.api.importChannelCondition,
                // 上传时附带的额外参数
                data: { id: 1 }
            },
            tableLoading: false
        };
    },
    computed: {
        dialogFormDisabled() {
            return this.dialogTitle == '详情'
        }
    },
    created() {
    },
    mounted() {
        this.handleCommand('a')
        this.getChannelCondition();
        this.getChannelGroupSet()
    },
    methods: {
        /**
         * 查询
         */
        searchTable() {
            this.$refs['formData'].searchForm('form');
        },
        /**
         * form组件内置查询事件
         */
        searchForm(val) {
            if (val) {
                this.getChannelCondition();
            }
        },
        /**
         * 每页条数变化事件
         */
        handleSizeChange(val) {
            this.pagination.pageNum = 1;
            this.pagination.pageSize = val;
            this.getChannelCondition();
        },
        /**
         * 改变分页触发事件
         */
        handleChangePage(val) {
            this.pagination.pageNum = val;
            this.getChannelCondition();
        },
        /**
         * 单选
         */
        handleCurrentChange(val) {
            this.currentRow = val
        },
        /**
         * 清除数据
         */
        clearParams() {
            this.resetForm('formData')
        },
        /**
         * 重置表单
         */
        resetForm(formName) {
            this.$refs[formName].resetForm('form');
            for (let k in this[formName]) {
                if (Object.prototype.toString.call(this[formName][k]) == "[object String]") {
                    this[formName][k] = ''
                } else if (Object.prototype.toString.call(this[formName][k]) == "[object Array]") {
                    this[formName][k] = []
                } else if (Object.prototype.toString.call(this[formName][k]) == "[object Number]") {
                    this[formName][k] = ''
                }
            }
        },

        /**
         * 获取通道组数据
         */
        getChannelGroupSet() {
            let postData = {
                pageSize: 9999,
                total: 0,
                pageNum: 1,
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.$httpGet(window.api.getChannelGroupSet, postData).then(res => {

                if (res.code == 200 && res.rows) {
                    this.belongGroupIdList = res.rows
                } else {
                }
            }).catch(err => {

            });
        },


        changeBelongGroupName(val) {
            this.belongGroupIdList.map((res) => {

                if (res.id == val) {

                    this.dialogFormData.belongGroupName = res.groupName
                }
            })
        },
        /**
         * 下拉菜单指令
         * @param {*} command 
         */
        handleCommand(command) {
            let timeObj = {
                a: 1 * 60 * 1000,
                b: 2 * 60 * 1000,
            }
            this.renovateTime = timeObj[command]
            if (this.renovateTimeInterval) {
                clearInterval(this.renovateTimeInterval)
            }
            this.renovateTimeInterval = setInterval(() => {
                this.getChannelCondition()
            }, this.renovateTime)
        },
        /**
         * 刷新
         */
        renovateTimeClick() {

            this.$httpGet(window.api.refreshOnlineStatus, { refreshTime: this.renovateTime, channelId: "" }).then(res => {

                if (res.code == 200) {
                    // this.pagination.total = res.total;
                    // this.dataSource = res.rows;
                    this.getChannelCondition()

                } else {
                }
            }).catch(err => {

            });
        },
        /**
         * 新增
         */
        addTable() {
            this.dialogTitle = '新增'
            this.dialogShow = true
            this.dialogFormData.identification = true
            this.dialogFormData.channelStatus = 1
            this.getChannelGroupSet()
        },
        /**
         * 表格-删除
         */
        tbRowdetele(row) {
            this.$confirm('确定要删除【' + row.channelName + '】吗？', '确认删除', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.delChannelSet(row)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        /**
         * 删除表格数据
         */
        delChannelSet(row) {
            let postData = {
                channelId: row.channelId
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.dataSource = [];
            this.$httpGet(window.api.delChannelSet, postData).then(res => {
                if (res.code == 200) {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getChannelCondition()
                } else {
                }
            }).catch(err => {

            });
        },
        /**
         * 设置为主通道
         */
        openMainChannel(row) {
            this.$confirm('是否将此通道设置为主通道，后续系统计算以主通道数据为准。', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.setMainChannel(row)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        /**
         * dialogFormData组件内置提交事件
         */
        diaSubmitForm(val) {
            if (val) {
                if (this.dialogTitle == '编辑') {
                    this.addChannelCondition()
                } else if (this.dialogTitle == '新增') {
                    this.addChannelCondition()
                }
            }
        },
        /**
         * 弹窗-单点新增-保存
         */
        diaSave() {
            this.$refs['dialogFormData'].submitForm('form');

        },
        /**
         * 弹窗-单点新增-关闭
         */
        diaClose() {
            this.dialogShow = false
            this.dialogBatchShow = false
            this.resetForm('dialogFormData')
        },
        /**
         * 获取表格数据
         */
        getChannelCondition() {
            let postData = {
                ...this.formData,
                ...this.pagination
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.dataSource = [];
            this.tableLoading = true
            this.$httpGet(window.api.getChannelCondition, postData).then(res => {
                if (res.code == 200 && res.rows) {
                    this.pagination.total = res.total;
                    this.dataSource = res.rows;
                } else {
                }
                this.tableLoading = false
            }).catch(err => {
                this.tableLoading = false
            });
        },
        /**
         * 新增接口
         */
        addChannelCondition() {
            let postData = {
                ...this.dialogFormData,
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.$httpPost(window.api.addChannelCondition, postData).then(res => {
                if (res.code == 200) {
                    this.$message({
                        message: '成功',
                        type: 'success'
                    })
                    this.getChannelCondition()
                    this.diaClose()
                } else {
                }
            }).catch(err => { });
        },
        /**
         * 设置为主通道
         */
        setMainChannel(row) {
            let postData = {
                id: row.id
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.dataSource = [];
            this.$httpPost(window.api.setMainChannel, postData).then(res => {
                if (res.success) {
                    this.$message({
                        type: 'success',
                        message: '成功!'
                    });
                    this.getChannelCondition()
                } else {
                }
            }).catch(err => {

            });
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$message({
                message: response.message,
                type: 'success'
            })
            this.searchTable();
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        },
        /**
         * 表格-编辑
         */
        openEdit(row) {
            this.dialogTitle = '编辑'
            Object.assign(this.dialogFormData, row)
            this.dialogShow = true
            // this.dialogFormData.identification = true
            // this.dialogFormData.channelStatus = 1
            this.getChannelGroupSet()
        },
        /**
         * @Author: ybf
         * @LastEditTime: 
         * @description: 复制当前行通道
         * @return {*}
         */
        copyChannelSet(row) {
            this.$confirm('是否拷贝当前通道并新增', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                Object.assign(this.dialogFormData, row)
                this.dialogFormData.id = ''
                this.dialogFormData.channelId = ''
                this.dialogFormData.isOnline = ''
                this.dialogFormData.channelName = this.dialogFormData.channelName + '-副本'
                this.addChannelCondition()
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        }
    }
};
</script>
    
<style scoped lang="scss">
.channelCondition {
    height: calc(100vh - 70px);
}

.searchForm {
    // height: calc(100% - 40px);
    display: flex;
    align-items: center;
    position: relative;
}

.submitForm {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
}

.btnBox {
    display: flex;
    float: right;
    z-index: 10;
    position: absolute;
    top: 15px;
    right: 10px;
}

.dialogHeaderSearch {
    background-color: var(--model-bgc);
    padding: 10px;
    margin-top: 10px;
    display: flex;
    flex-wrap: wrap;
    justify-content: right;

    .el-form-item {
        margin-bottom: 4px;

        ::v-deep .el-form-item__error {
            padding-top: 0;
        }
    }
}

::v-deep .el-upload {
    width: 100%;

    .el-upload-dragger {
        width: auto;
    }
}

::v-deep .el-dropdown {
    position: absolute;
    right: 10px;
    top: 2px;
}

::v-deep .el-button--primary {
    background-color: rgba(71, 99, 255, 1);
    border-color: rgba(71, 99, 255, 1);
}

.dropdownBtn ::v-deep .el-button-group .el-button--primary {
    height: 32px;
}
</style>
    
    